#ifndef PA_INTERFACE_H
#define PA_INTERFACE_H

#include "AudioInterface.h"
#include "Singleton.h"
#include <map>
#include <vector>
#include <portaudio.h>

class AudioReceiver;

class PAInterface : public AudioInterface, public Uncopyable
{
public:
	bool Init(unsigned int sampleRate, bool interleaved = true);
	void LoadTracks(const std::string& filePaths);

	void LoadTrack(int id, const std::vector<float>& table);
	void LoadTemporaryWaveTable(std::vector<float>* waveTable); 
	
	int LoadSinTable(int id, float amplitudeScalar, float frequency, float duration);
	void PlayTrack(int trackID, bool loop = false);
	void PlayTrack(int trackID, bool loop, float* sourceX, float* sourceY, float* sourceZ); 

	void Work();
	void MixToBuffer();
	void PositionSound(float* leftScalar, float* rightScalar, float xSource, float ySource, float zSource);

	bool StartStream();
	void StopStream();
	void PAError(int error);

	~PAInterface();


	struct RunningTrack
	{
		RunningTrack() : m_trackID(-1), m_readIndex(-1), m_length(-1), 
			m_positional(false), m_loop(false), m_temporary(false), m_pSourceX(0), 
				m_pSourceY(0), m_pSourceZ(0) {}
		int m_trackID;
		int m_readIndex;
		int m_length;
		bool m_positional;
		bool m_loop;
		bool m_temporary;
		std::vector<float>* m_pTempTable;
		float* m_pSourceX;
		float* m_pSourceY;
		float* m_pSourceZ;
	};

	

private:
	PAInterface();
	friend class Singleton<PAInterface>;

	unsigned int m_sampleRate;

	float m_buffers[CHANNELS][FRAMES_PER_BUFFER];
	typedef std::map<int,std::vector<float>*> WaveTables;
	typedef std::vector<RunningTrack> RunningTracks;
	WaveTables m_waveTables;
	RunningTracks m_runningTracks;
	AudioReceiver* m_pAudioReceiver;

	PaStreamParameters m_outStreamParameters;
	PaStream* m_pStream;

};
typedef Singleton<PAInterface> ThePAInterface;

#endif